package com.sanmubird.mywebframework.utils;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections4.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 图片相关的工具类
 *
 * @author GMaya
 * @dateTime 2022/3/29 14:21
 */
public class ImageUtil {

    private static final int MARGIN = 3;
    private static final float LIMIT_SIZE = 100 * 1024;

    private static final Pattern r = Pattern.compile("[\\u4E00-\\u9FA5]");


    public static void compress(File file) throws IOException {
        // 如果图片小于指定压缩大小，则直接返回。
        byte[] allBytes = FileUtil.readBytes(file);
        if (allBytes.length < LIMIT_SIZE) {
            return;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //scale(比例),outputQuality(质量)
        Thumbnails.of(file).scale(0.25f).outputQuality(0.5f).toOutputStream(out);
        byte[] bytes = out.toByteArray();
        // 写入最终文件
        FileUtil.writeBytes(bytes, file);
    }

    public static void compress(String filePath) throws IOException {
        File file = new File(filePath);
        compress(file);
    }


    /**
     * 图片加水印
     *
     * @param pressTextList 水印文字
     * @param file          要加水印的图片
     */
    public static void waterMark(String title, List<String> pressTextList, File file) throws IOException {
        BufferedImage src = ImageIO.read(file);
        int width = src.getWidth(null);
        int height = src.getHeight(null);

//        System.out.println("图片宽高：" + width + " * " + height);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        // 将原内容画上去
        g.drawImage(src, 0, 0, width, height, null);
        /* 消除java.awt.Font字体的锯齿 */
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.7f));

        // 绘制边框
        int border_width = width * 618 / 1000;
        int y_top_start = height * 618 / 1000;
        int x_start = width * MARGIN / 100;
        int borderFontSize = x_start * 3 / 2;
        int text_start = x_start + borderFontSize;
        g.setFont(new Font("黑体", Font.BOLD, borderFontSize));

        int y_bottom_start = height - borderFontSize * 2 - height * MARGIN / 100;
        int center_height = y_bottom_start - y_top_start;
        int center_width = border_width - borderFontSize - MARGIN;
        int max_word_count = center_width / borderFontSize;

        // 绘制上边框
        g.setColor(Color.BLUE);
        g.fillRect(x_start, y_top_start, border_width, borderFontSize * 2);
        g.setColor(Color.WHITE);
        g.drawString(title, text_start, y_top_start + borderFontSize + borderFontSize / 3);

        // 绘制中建边框
        g.setColor(Color.WHITE);
        g.fillRect(x_start, y_top_start + borderFontSize * 2, border_width, center_height);
        g.setColor(Color.BLACK);

        // 绘制文字
        List<String> new_pressTextList = pressTextList.stream()
                .map(str -> Arrays.stream(StrUtil.split(str, max_word_count)).collect(Collectors.toList()))
                .flatMap(List::stream)
                .collect(Collectors.toList());
        //
        int centFontSize = borderFontSize;
        int maxFontSize = center_height / new_pressTextList.size() / 2;
        if (maxFontSize < borderFontSize) {
            centFontSize = maxFontSize;
        }
//        System.out.printf("边框字体大小%s, 中间字体大小%s", borderFontSize, centFontSize);

        for (int i = 0, l = new_pressTextList.size(); i < l; i++) {
            String text = new_pressTextList.get(i);
            g.drawString(text, text_start, y_top_start + borderFontSize + (centFontSize * 15 / 10) * (2 + i));
        }

        // 绘制下边框
        g.setColor(Color.BLUE);
        g.fillRect(x_start, y_bottom_start, border_width, borderFontSize * 2);
        g.setColor(Color.WHITE);
        g.drawString(title, text_start, y_bottom_start + borderFontSize + borderFontSize / 3);

        // 输出图像
        g.dispose();

        String name = file.getName();
        ImageIO.write(image, name.substring(name.lastIndexOf(".") + 1), file);

    }

    public static List<String> splitByWidth(String str, int width) {
        System.out.println(str);
        int total = width * 2;
        int index = 0;
        int currentLine = 1;
        List<String> content = Lists.newArrayList();
        String[] split = str.split("");
        List<String> fragment = Lists.newArrayList();
        for (String s : split) {
            Matcher m = r.matcher(s);
            if (m.matches()) {
                index += 2;
            } else {
                index += 1;
            }
            fragment.add(s);
            int lineNumber = index / total;
            if (lineNumber >= currentLine) {
                currentLine += 1;
                content.add(StrUtil.join("", fragment));
                fragment = Lists.newArrayList();
            }
        }
        if (CollectionUtils.isNotEmpty(fragment)) {
            content.add(StrUtil.join("", fragment));
        }
        return content;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        splitByWidth("占山zs1大家11 http://www背景aaa.com?aob=11&aa=@#河南", 5);
    }

}


